package com.wpw.java8demo;

import java.util.Optional;

import org.junit.Test;

public class OptionalTest {
	
	private Apple apple = new Apple(1, "red");
	private Optional<Apple> appOptional = Optional.of(apple);
	
	@Test
	public void test1() {

		Optional<Apple> empty = Optional.empty();
		System.out.println(empty.orElse(apple));
		
		Optional<Apple> appOptional = Optional.of(apple);
		System.out.println(appOptional.get());
		
		Optional<Apple> nullApple = Optional.ofNullable(null);
		System.out.println(nullApple.orElse(apple));
		
		System.out.println(nullApple.equals(empty));
	}
	
	@Test
	public void test2() {
		Optional<Apple> appOptional = Optional.of(apple);
		Optional<String> colorOptional = appOptional.map(Apple::getColor);
		System.out.println(colorOptional.get());
		
		Optional<Apple> appOptional2 = Optional.empty();
		Optional<String> colorOptional2 = appOptional2.map(Apple::getColor);
		System.out.println(colorOptional2.orElse("null"));
		
		Optional<Apple> appOptional3 = Optional.of(apple);
		apple.setBug(Optional.empty());
		//appOptional3.map(Apple::getBug).map(Bug::getName); //编译失败，Apple.getBug()返回的类型是Optional<Bug>,所以这里调用map后返回的类型是Optional<Optional<Bug>>
		Optional<Bug> bug = appOptional3.flatMap(Apple::getBug);
		String bugName = bug.map(Bug::getName).orElse("unKnown");
		System.out.println(bugName);
	}

	
	@Test
	public void test3() {
		appOptional.ifPresent((a) -> {
			System.out.println(a.getColor());
		});
	}

	@Test
	public void test4() throws Exception {
		apple.setBug(Optional.empty());
		appOptional.flatMap(Apple::getBug)
			.orElseThrow(() -> {
				return new Exception();
			});
	}
	
	@Test
	public void test5() {
		Optional<Apple> filter = appOptional.filter((a) -> {
			return a.getColor().equals("red");
		});
		System.out.println(filter.get());
	}
	
}
